package com.hss.common.helper;

import android.content.Context;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.SyncHttpClient;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.NameValuePair;


public class AsyncHttpHelper extends AsyncHttpClient {

//	shietion.vicp.net:9099
//	/rest/acs/ service
	private static final int TIME_OUT = 25000;
	private static final String BASE_URL = "http://api.fss.com/1/";

	private static AsyncHttpHelper instance;

	private AsyncHttpHelper() {
		setTimeout(TIME_OUT);


		// **************https代码*****************

		// this.setSSLSocketFactory(SSLSocketFactory.getSocketFactory());

		// https代码
		// InputStream ff = null;
		// try {
		// KeyStore trustStore;
		// trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
		// try {
		// ff = mContext.getAssets().open("clientKeystore.bks");
		// } catch (Exception e) {
		// }
		// trustStore.load(ff, "qinyic789012".toCharArray());
		// SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
		// sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		//
		// this.setSSLSocketFactory(sf);
		// } catch (KeyStoreException e) {
		// e.printStackTrace();
		// } catch (NoSuchAlgorithmException e) {
		// e.printStackTrace();
		// } catch (CertificateException e) {
		// e.printStackTrace();
		// } catch (IOException e) {
		// e.printStackTrace();
		// } catch (KeyManagementException e) {
		// e.printStackTrace();
		// } catch (UnrecoverableKeyException e) {
		// e.printStackTrace();
		// } finally {
		// }
		// **************https代码*****************
	}

	// private static class MySSLSocketFactory extends SSLSocketFactory {
	// SSLContext sslContext = SSLContext.getInstance("TLS");
	//
	// public MySSLSocketFactory(KeyStore truststore)
	// throws NoSuchAlgorithmException, KeyManagementException,
	// KeyStoreException, UnrecoverableKeyException {
	// super(truststore);
	//
	// TrustManager tm = new X509TrustManager() {
	// @Override
	// public X509Certificate[] getAcceptedIssuers() {
	// return null;
	// }
	//
	// @Override
	// public void checkServerTrusted(X509Certificate[] chain,
	// String authType) throws CertificateException {
	// }
	//
	// @Override
	// public void checkClientTrusted(X509Certificate[] chain,
	// String authType) throws CertificateException {
	// }
	// };
	//
	// KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
	// kmf.init(truststore, "qinyi123456".toCharArray());
	//
	// sslContext.init(kmf.getKeyManagers(), new TrustManager[] { tm },
	// null);
	// }
	//
	// @Override
	// public Socket createSocket() throws IOException {
	// return sslContext.getSocketFactory().createSocket();
	// }
	//
	// @Override
	// public Socket createSocket(Socket socket, String host, int port,
	// boolean autoClose) throws IOException, UnknownHostException {
	//
	// return sslContext.getSocketFactory().createSocket(socket, host,
	// port, autoClose);
	// }
	// }

	public static AsyncHttpHelper getInstance() {
		if (null == instance) {
			instance = new AsyncHttpHelper();
		}
		return instance;
	}

	public void getWithCookie(Context context, String url,
			AsyncHttpResponseHandler responseHandler) {
		PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
		// myCookieStore.clear();
		setCookieStore(myCookieStore);

		get(url, responseHandler);
		// Iterator iterator = myCookieStore.getCookies().iterator();
		// while (iterator.hasNext()) {
		// Cookie cookie = (Cookie) iterator.next();
		// LogUtils.d("cookie name--" + cookie.getName());
		// LogUtils.d("cookie value--" + cookie.getValue());
		// }

		// BasicCookieStore basicCookieStore = new BasicCookieStore();
		//
		// client.setCookieStore(basicCookieStore);
		// client.get(getAbsoluteUrl(url), responseHandler);
		// Iterator iterator = basicCookieStore.getCookies().iterator();
		// while (iterator.hasNext()) {
		// Cookie cookie = (Cookie) iterator.next();
		// LogUtils.d("sssss" + cookie.getName());
		// LogUtils.d("sssss" + cookie.getValue());
		// }

	}

	/*public void getUseCookie(Context context, String url, HashMap hashMap,
			AsyncHttpResponseHandler responseHandler) {
		PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
		if (null != hashMap && hashMap.size() > 0) {
			Iterator iterator = hashMap.entrySet().iterator();
			while (iterator.hasNext()) {
				Map.Entry entry = (Map.Entry) iterator.next();
				Object key = entry.getKey();
				Object value = entry.getValue();
				Cookie cookie = new BasicClientCookie(key.toString(),
						value.toString());
				myCookieStore.addCookie(cookie);
			}
		}
		setCookieStore(myCookieStore);
		get(url, responseHandler);
	}*/

	public void getWithCookie(Context context, String url,
			RequestParams params, AsyncHttpResponseHandler responseHandler) {
		PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
		setCookieStore(myCookieStore);
		get(url, params, responseHandler);
	}

	public void postWithCookie(Context context, String url,
			AsyncHttpResponseHandler responseHandler) {
		PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
		// myCookieStore.clear();
		setCookieStore(myCookieStore);
		post(url, responseHandler);
	}

	public void postWithCookie(Context context, String url,
			RequestParams params, AsyncHttpResponseHandler responseHandler) {
		PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
		setCookieStore(myCookieStore);
		post(url, params, responseHandler);
	}

//	public void postUseCookie(Context context, String url, HashMap hashMap,
//			AsyncHttpResponseHandler responseHandler) {
//		PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
//		if (null != hashMap && hashMap.size() > 0) {
//			Iterator iterator = hashMap.entrySet().iterator();
//			while (iterator.hasNext()) {
//				Map.Entry entry = (Map.Entry) iterator.next();
//				Object key = entry.getKey();
//				Object value = entry.getValue();
//				Cookie cookie = new BasicClientCookie(key.toString(),
//						value.toString());
//				myCookieStore.addCookie(cookie);
//			}
//		}
//		setCookieStore(myCookieStore);
//		post(url, responseHandler);
//	}

	public static String getUrlFromHashMap(String originUrl, HashMap hashMap) {
		String returnUrl = originUrl;

		if (null != hashMap && hashMap.size() > 0) {
			returnUrl = returnUrl + "?";
			Iterator iterator = hashMap.entrySet().iterator();
			while (iterator.hasNext()) {
				Map.Entry entry = (Map.Entry) iterator.next();
				Object key = entry.getKey();
				Object value = entry.getValue();
				returnUrl += key + "=" + value + "&";
			}
			if (returnUrl.endsWith("&")) {
				returnUrl = returnUrl.substring(0, returnUrl.length() - 1);
			}
		}
		// LogUtils.d(returnUrl);
		return returnUrl;
	}

	public static void uploadFiles(String url, List<NameValuePair> paramsList,
			String fileParams, List<File> files,
			AsyncHttpResponseHandler responseHandler) {
		SyncHttpClient syncHttpClient = new SyncHttpClient();

		RequestParams params = new RequestParams();
		try {
			if (null != paramsList && paramsList.size() > 0) {
				for (NameValuePair nameValuePair : paramsList) {
					params.put(nameValuePair.getName(),
							nameValuePair.getValue());
				}
			}
			if (null != files && files.size() > 0)
				params.put(fileParams, files);
		} catch (Exception e) {
			// LogUtils.e(e.getMessage());
		}
		syncHttpClient.setTimeout(TIME_OUT);
		syncHttpClient.post(url, params, responseHandler);

	}

	/**
	 * @param url
	 *            要下载的文件URL
	 * @throws Exception
	 */
	/*
	 * public static void downloadFile(String url) throws Exception {
	 *
	 * AsyncHttpClient client = new AsyncHttpClient(); // 指定文件类型 String[]
	 * allowedContentTypes = new String[] { "image/png", "image/jpeg" }; //
	 * 获取二进制数据如图片和其他文件 client.get(url, new
	 * BinaryHttpResponseHandler(allowedContentTypes) {
	 *
	 * @Override public void onSuccess(int statusCode, Header[] headers, byte[]
	 * binaryData) { String tempPath = Environment.getExternalStorageDirectory()
	 * .getPath() + "/temp.jpg"; // TODO Auto-generated method stub //
	 * 下载成功后需要做的工作 progress.setProgress(0); // Log.e("binaryData:", "共下载了：" +
	 * binaryData.length); // Bitmap bmp =
	 * BitmapFactory.decodeByteArray(binaryData, 0, binaryData.length);
	 *
	 * File file = new File(tempPath); // 压缩格式 CompressFormat format =
	 * Bitmap.CompressFormat.JPEG; // 压缩比例 int quality = 100; try { // 若存在则删除 if
	 * (file.exists()) file.delete(); // 创建文件 file.createNewFile(); //
	 * OutputStream stream = new FileOutputStream(file); // 压缩输出
	 * bmp.compress(format, quality, stream); // 关闭 stream.close(); //
	 * Toast.makeText(mContext, "下载成功\n" + tempPath, Toast.LENGTH_LONG).show();
	 *
	 * } catch (IOException e) { // TODO Auto-generated catch block
	 * e.printStackTrace(); }
	 *
	 * }
	 *
	 * @Override public void onFailure(int statusCode, Header[] headers, byte[]
	 * binaryData, Throwable error) { // TODO Auto-generated method stub
	 * Toast.makeText(mContext, "下载失败", Toast.LENGTH_LONG).show(); }
	 *
	 * @Override public void onProgress(int bytesWritten, int totalSize) { //
	 * TODO Auto-generated method stub super.onProgress(bytesWritten,
	 * totalSize); int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
	 * // 下载进度显示 progress.setProgress(count); Log.e("下载 Progress>>>>>",
	 * bytesWritten + " / " + totalSize);
	 *
	 * }
	 *
	 * @Override public void onRetry(int retryNo) { // TODO Auto-generated
	 * method stub super.onRetry(retryNo); // 返回重试次数 }
	 *
	 * }); }
	 */

	/**
	 * @param path
	 *            要上传的文件路径
	 * @param url
	 *            服务端接收URL
	 * @throws Exception
	 */
	/*public static void uploadFile(String path, String url) throws Exception {
		File file = new File(path);
		if (file.exists() && file.length() > 0) {
			AsyncHttpClient client = new AsyncHttpClient();
			RequestParams params = new RequestParams();
			params.put("uploadfile", file);
			// 上传文件
			client.post(url, params, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, Header[] headers,
						byte[] responseBody) {
					// 上传成功后要做的工作
					Toast.makeText(mContext, "上传成功", Toast.LENGTH_LONG).show();
					progress.setProgress(0);
				}

				@Override
				public void onFailure(int statusCode, Header[] headers,
						byte[] responseBody, Throwable error) {
					// 上传失败后要做到工作
					Toast.makeText(mContext, "上传失败", Toast.LENGTH_LONG).show();
				}

				@Override
				public void onProgress(int bytesWritten, int totalSize) {
					// TODO Auto-generated method stub
					super.onProgress(bytesWritten, totalSize);
					int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
					// 上传进度显示
					progress.setProgress(count);
					Log.e("上传 Progress>>>>>", bytesWritten + " / " + totalSize);
				}

				@Override
				public void onRetry(int retryNo) {
					// TODO Auto-generated method stub
					super.onRetry(retryNo);
					// 返回重试次数
				}

			});
		} else {
			Toast.makeText(mContext, "文件不存在", Toast.LENGTH_LONG).show();
		}

	}*/

}
